/**
 * Author: ligj@mapbar.com
 * Create Time: 2018/03/23 15:40
 * Description:
 */
import Vue from 'vue'
import axios from 'axios'
/**
 * 图吧地图组件
 * 示例： <m-map :on-load="mapLoad" center="116.40049,39.9208" style="width: 100%;height: 200px;"/>
 *       mapLoad: function(maplet){}
 */

const loadMapApi = function (url, callback, errorCallback) {
    let script = document.createElement('script')
    script.type = 'text/javascript'
    let params = {
        window: window
    }
    function getCallbackParams () {
        return params
    }
    if (script.readyState) { // IE
        script.onreadystatechange = function () {
            if (script.readyState === 'loaded' || script.readyState === 'complete') {
                script.onreadystatechange = null
                callback(getCallbackParams())
            }
        }
    } else { // Others
        script.onload = function () {
            callback(getCallbackParams())
        }
    }
    script.onerror = function () { // 顺序必须在append之前
        errorCallback(getCallbackParams())
    }
    script.src = url

    document.body.appendChild(script)
}

let isFetching = false, mapletPromise = null
const getMaplet = function () {
    if (!isFetching) {
        isFetching = true
        mapletPromise = new Promise((resolve, reject) => {
            if (window['Maplet']) {
                isFetching = false
                resolve(window['Maplet'])
            } else {
                loadMapApi(
                    'http://api.mapbar.com/api/mapbard31.4.js',
                    () => {
                        Vue.nextTick(() => {
                            isFetching = false
                            resolve(window['Maplet'])
                        })
                    }),
                    (err) => {
                        isFetching = false
                        reject(err)
                    }
            }
        })
    }
    return mapletPromise
}

export default {
    data () {
        return {
            maplet: null,
            radius: ''
        }
    },
    props: {
        center: String,
        zoom: Number,
        onLoad: Function
    },
    methods: {
        mapResize () {
            if (this.maplet) { // 自适应外部尺寸
                this.maplet.resize(this.$el.offsetWidth, this.$el.offsetHeight)
            }
        },
        documentClick () {
            this.$timeout(() => {
                if (this.$el.getBoundingClientRect().width > 0) {
                    this.mapResize()
                }
            })
        },
        // 激活地图标注功能
        mapMarker () {
            this.maplet.clearOverlays()
            MEvent.addListener(this.maplet, "bookmark", this.bookmark_done)
            this.maplet.setMode('bookmark', this.bookmark_done)
            this.maplet.setCursorIcon('static/centerMarker.png')
        },
        bookmark_done (data) {
            var point = data.point
            var icon = new MIcon('static/centerMarker.png', 28, 28, 15 ,30)
            var marker = new MMarker( point,icon )
            marker.dragAnimation = false
            this.maplet.addOverlay(marker)
            this.maplet.setCursorIcon("")
            this.maplet.setMode("pan")

            var obj = new Object()
            obj["lon"] = data.point.lon
            obj["lat"] = data.point.lat
            this.$emit('markDone', obj)
        },
        // 读取默认经纬度位置
        showDefault (lonlat) {
            this.maplet.clearOverlays()
            var point = new MPoint(lonlat)
            var icon = new MIcon('static/centerMarker.png', 28, 28, 15 ,30)
            var marker = new MMarker(point, icon)
            marker.dragAnimation = false
            this.maplet.addOverlay(marker)
            this.maplet.setCursorIcon("")
            this.maplet.setMode("pan")
            // 设置中心点和等级
            this.maplet.setCenter(new MPoint(lonlat));
            this.maplet.setZoomLevel(8);
        },
        // 标注多边形区域
        polygonArea () {
            this.maplet.addControl(new MStandardControl());
            this.maplet.showOverview(false);

            this.maplet.setMode("drawarea",this.drawPolygon);
        },
        // 根据画的点生成面
        drawPolygon(dataObj) {
            this.maplet.setMode("pan");

            //初始化画笔
            let brush = new MBrush("green");
            brush.stroke = 2;
            brush.fill = true;
            brush.color = "green";
            brush.bgcolor = "gray";
            brush.bgtransparency = 35;
            //初始化多边形
            let polygon = new MPolyline(
                dataObj.points,
                brush
            );
            polygon.setEditable(false);
            this.maplet.addOverlay(polygon);
            this.maplet.setAutoZoom()
            this.$emit('polygonDone', dataObj.points)
        },
        // 设置中心点和放大级别
        setCenterAndZoom (point, zoom, districtCode, level, type) {
            if (type == 'D') {
                this.makeDistrictArea(districtCode,level)
            }else if(type == 'DA'){// 'DA' 代表电子围栏报警信息中的位置查看
                this.makeDistrictAreaForAlarm(districtCode,level)
            }
            else{
                let lonlat=point.split(',')
                this.maplet.centerAndZoom(new MPoint(lonlat[0],lonlat[1]), zoom);
            }
        },
        // 绘制省市区边界
        makeDistrictArea(districtCode,level){
            var url='http://w.mapbar.com/city/'
            if(level === 'country'){
                url=url+'getAreaDetail.json?encode=utf-8&isLonlats=true&district='+districtCode
            }else{
                url=url+'getCityDetail.json?isDetail=true&encode=utf-8&type='+level+'&city='+districtCode
            }
            url+="&_rid="+Math.random()
            axios.post(url).then(res => {
                let data = res.data
                if(data.status='200'){
                    let centerPoint=data.result.city[0].centerLonLat.split(',')
                    let zoom=data.result.city[0].zoom
                    this.maplet.centerAndZoom(new MPoint(centerPoint[0],centerPoint[1]), zoom)
                    //边界
                    let lltmp
                    let pointArray=[]
                    let pointStr

                    this.maplet.clearOverlays()
                    for(let j=0;j<data.result.city[0].lonlats.lonlats.length;j++){
                        pointStr=data.result.city[0].lonlats.lonlats[j].item
                        let llArray=pointStr.split(';')
                        for(let i=0;i<llArray.length;i++){
                            if(llArray[i]=='')continue
                            lltmp=llArray[i].split(',')
                            pointArray.push(new MPoint(lltmp[0],lltmp[1]))
                        }
                        this.makePolyLine(pointArray)
                        pointArray=[]
                    }
                    this.maplet.setAutoZoom()
                }
            }).catch(e => {
                this.$message.error('获取省市区信息失败',e)
            })
        },
        // 绘制报警信息中的省市区边界
        makeDistrictAreaForAlarm(districtCode,level){
            var url='http://w.mapbar.com/city/'
            if(level === 'country'){
                url=url+'getAreaDetail.json?encode=utf-8&isLonlats=true&district='+districtCode
            }else{
                url=url+'getCityDetail.json?isDetail=true&encode=utf-8&type='+level+'&city='+districtCode
            }
            url+="&_rid="+Math.random()
            axios.post(url).then(res => {
                let data = res.data
                if(data.status='200'){
                    let centerPoint=data.result.city[0].centerLonLat.split(',')
                    let zoom=data.result.city[0].zoom
                    this.maplet.centerAndZoom(new MPoint(centerPoint[0],centerPoint[1]), zoom)
                    //边界
                    let lltmp
                    let pointArray=[]
                    let pointStr

                    //this.maplet.clearOverlays()
                    for(let j=0;j<data.result.city[0].lonlats.lonlats.length;j++){
                        pointStr=data.result.city[0].lonlats.lonlats[j].item
                        let llArray=pointStr.split(';')
                        for(let i=0;i<llArray.length;i++){
                            if(llArray[i]=='')continue
                            lltmp=llArray[i].split(',')
                            pointArray.push(new MPoint(lltmp[0],lltmp[1]))
                        }
                        this.makePolyLine(pointArray)
                        pointArray=[]
                    }
                    this.maplet.setAutoZoom()
                }
            }).catch(e => {
                this.$message.error('获取省市区信息失败',e)
            })
        },
        // 绘制折线
        makePolyLine (pointArray) {
            this.maplet.showOverview(false);
            let brush = new MBrush("green");
            brush.fill = true;
            brush.bgcolor = "gray";
            let polyline = new MPolyline(
                pointArray,
                brush
            );
            this.maplet.addOverlay(polyline);
        },
        // 标注圆形区域
        makeCircleArea(radius) {
            // 激活地图标注功能
            this.maplet.clearOverlays();
            this.maplet.setMode('bookmark', this.drawCirlce);
            this.maplet.setCursorIcon('static/centerMarker.png');
            this.radius = radius
        },
        // 根据经纬度标注圆形区域
        makeCircleAreaForLonAndLat(radius,circlePoint) {
            // 激活地图标注功能
            this.maplet.clearOverlays();
            this.radius = radius
            this.drawCirlceForLonAndLat(circlePoint)
            this.maplet.setCursorIcon('static/centerMarker.png');
        },
        //警报车辆位置
        drawErrorCarPoint(lon,lat) {
            let point = new MPoint(lon, lat)
            this.drawPoint({ point })
        },
        drawPoint(data) {
            let circlePoint = {}
            circlePoint = data.point;
            let icon = new MIcon('static/car_red.png', 28, 28, 15, 30);
            let marker = new MMarker(circlePoint, icon);
            marker.dragAnimation = false;
            this.maplet.addOverlay(marker);
            this.maplet.setCursorIcon("");
            this.maplet.setAutoZoom()
        },
        //警报车辆应在位置（行政区划）
        drawDefaultRegionForAlarm(centerLonLat) {
            let point = new MPoint(centerLonLat)
            let circlePoint = {}
            circlePoint = point;
            let icon = new MIcon('static/car_green.png', 28, 28, 15, 30);
            let marker = new MMarker(circlePoint, icon);
            marker.dragAnimation = false;
            this.maplet.addOverlay(marker);
            this.maplet.setCursorIcon("");
            this.maplet.setAutoZoom()
        },
        drawCirlce(data, zoom) {
            let circlePoint = {}
            this.maplet.clearOverlays();
            if(data !== null){
                circlePoint = data.point;
            }
            this.maplet.setCenter(circlePoint)
            let icon = new MIcon('static/centerMarker.png', 28, 28, 15, 30);
            let marker = new MMarker(circlePoint, icon);
            marker.dragAnimation = false;
            this.maplet.addOverlay(marker);
            this.maplet.setCursorIcon("");

            let brush = new MBrush();
            brush.color = "green";
            brush.bgcolor = "gray";
            brush.fill = true;
            brush.transparency = 80;
            brush.bgtransparency = 30;
            let ellipse = new MEllipse(circlePoint, this.radius, null, brush);
            this.maplet.addOverlay(ellipse);
            this.maplet.setMode("pan");
            this.maplet.setAutoZoom()
            this.$emit('circleDone', circlePoint)
        },
        drawCirlceForAlarm(data, zoom) {
            let circlePoint = {}
            this.maplet.clearOverlays();
            if(data !== null){
                circlePoint = data.point;
            }
            this.maplet.setCenter(circlePoint)
            let icon = new MIcon('static/car_green.png', 28, 28, 15, 30);
            let marker = new MMarker(circlePoint, icon);
            marker.dragAnimation = false;
            this.maplet.addOverlay(marker);
            this.maplet.setCursorIcon("");

            let brush = new MBrush();
            brush.color = "green";
            brush.bgcolor = "gray";
            brush.fill = true;
            brush.transparency = 80;
            brush.bgtransparency = 30;
            let ellipse = new MEllipse(circlePoint, this.radius, null, brush);
            this.maplet.addOverlay(ellipse);
            this.maplet.setMode("pan");
            this.maplet.setAutoZoom()
            this.$emit('circleDone', circlePoint)
        },
        drawCirlceForLonAndLat(data, zoom) {
            let point = new MPoint(data.lon + ',' + data.lat)
            let circlePoint = {}
            this.maplet.clearOverlays();
            if(point !== null){
                circlePoint = point;
            }
            this.maplet.setCenter(circlePoint)
            let icon = new MIcon('static/centerMarker.png', 28, 28, 15, 30);
            let marker = new MMarker(circlePoint, icon);
            marker.dragAnimation = false;
            this.maplet.addOverlay(marker);
            this.maplet.setCursorIcon("");

            let brush = new MBrush();
            brush.color = "green";
            brush.bgcolor = "gray";
            brush.fill = true;
            brush.transparency = 80;
            brush.bgtransparency = 30;
            let ellipse = new MEllipse(circlePoint, this.radius, null, brush);
            this.maplet.addOverlay(ellipse);
            this.maplet.setMode("pan");
            this.maplet.setAutoZoom()
            //this.$emit('circleDone', circlePoint)
        },
        // 加载默认圆
        drawDefaultCircle (data, radius) {
            let point = new MPoint(data)
            this.radius = radius
            this.drawCirlce({ point })
        },
        // 电子围栏报警加载圆（中心图片与其他地方不一样）
        drawDefaultCircleForAlarm (data, radius) {
            let point = new MPoint(data)
            this.radius = radius
            this.drawCirlceForAlarm({ point })
        },
        // 加载默认多边形
        drawDefaultPolygon (dataStr) {
            dataStr = dataStr.substring(1, dataStr.length -1)
            let data = dataStr.split('},{')
            if (data && data.length > 0) {
                let points = []
                for (let i = 0; i < data.length; i++) {
                    let lon = data[i].split('lon:')[1].split(',lat')[0]
                    let lat = data[i].split('lat:')[1].split('}')[0]
                    points.push(new MPoint(lon + ',' + lat))
                }
                this.drawPolygon({ points })
            }
        },
        // 清除地图上图形
        clearOverlays () {
            this.maplet.clearOverlays();
        },
        // 清除绘制功能
        clearDraw () {
            this.maplet.setMode("pan");
        }

    },
    async mounted () {
        // 初始化地图
        await getMaplet()
        this.maplet = new Maplet(this.$el.querySelector('div'))
        this.maplet.centerAndZoom(new MPoint(this.$props.center || '116.40049,39.9208'), this.$props.zoom || 10)
        this.maplet.addControl(new MStandardControl())
        this.maplet.showOverview(true, false)
        this.mapResize()
        window.addEventListener('resize', this.mapResize)
        document.addEventListener('click', this.documentClick)
        this.onLoad && this.onLoad(this.maplet)
    },
    destroyed () {
        if (this.maplet) {
            window.removeEventListener('resize', this.mapResize)
            document.removeEventListener('click', this.documentClick)
            this.maplet.finalize()
        }
    },
    activated () {
        if (this.maplet) {
            this.mapResize()
            window.addEventListener('resize', this.mapResize)
            document.addEventListener('click', this.documentClick)
        }
    },
    deactivated () {
        if (this.maplet) {
            window.removeEventListener('resize', this.mapResize)
            document.removeEventListener('click', this.documentClick)
        }
    },
    render () {
        return <div><div></div></div>
    }

}
